JavaScript: why `null == 0` is false?
Posted
by lemonedo
on Stack Overflow
See other posts from Stack Overflow
or by lemonedo
Published on 2010-05-26T06:19:32Z
Indexed on
2010/05/26
6:31 UTC
Read the original article
Hit count: 233
I had to write a routine that increments the value of a variable by 1 if it is a number, or assigns 0 to the variable if it is not a number. The variable can be incremented by the expression, or be assigned null
. No other write access to the variable is allowed. So, the variable can be in three states: it is 0, a positive integer, or null
.
My first implementation was: v >= 0 ? v += 1 : v = 0
(Yes, I admit that v === null ? v = 0 : v += 1
is the exact solution, but I wanted to be concise then.)
It failed since null >= 0
is true. I was confused, since if a value is not a number, an numeric expression involving it must be false always. Then I found that null
is like 0, since null + 1 == 1
, 1 / null == Infinity
, Math.pow(2.718281828, null) == 1
, ...
Strangely enough, however, null == 0
is evaluated to false. I guess null
is the only value that makes the following expression false: (v == 0) === (v >= 0 && v <= 0)
So why null
is so special in JavaScript?
© Stack Overflow or respective owner